from flask import Blueprint, session, request
from flask_login import login_user, login_required, logout_user

from apps.common.result import fail, success
from apps.models.Users import User

passport_bp = Blueprint('passport', __name__, url_prefix='/auth')


# 登录
@passport_bp.post('/init/<id>')
def init_user(id):
    user = User.query.filter_by(id=id).first()
    User.query.filter_by(id=id).update({
        "password": user.gen_password("1")
    })
    return success()


# 登录
@passport_bp.post('/login')
def login_post():
    req = request.form
    username = req.get('username')
    password = req.get('password')

    if not username or not password:
        return fail(msg="用户名或密码没有输入")

    user = User.query.filter_by(username=username).first()

    if user is None:
        return fail(msg="不存在的用户")

    if user.deleted == 1:
        return fail(msg="用户被暂停使用")

    if username == user.username and user.validate_password(password):
        # 登录
        login_user(user)
        # 记录登录日志
        # login_log(request, uid=user.id, is_access=True)
        # 存入权限
        return success(msg="登录成功")
    return fail(msg="用户名或密码错误")


# 退出登录
@passport_bp.post('/logout')
@login_required
def logout():
    logout_user()
    session.pop('permissions')
    return success(msg="注销成功")


@passport_bp.get('/menu.json')
def menu():
    return success(data=
    {
        "menuInfo": [
            {
                "title": "首页",
                "icon": "fa fa-home",
                "href": "/home",
                "target": "_self"
            }, {
                "title": "管理",
                "icon": "fa fa-address-book",
                "target": "_self",
                "child": [
                    {
                        "title": "主页模板",
                        "href": "/crawler/index",
                        "target": "_self",
                    }
                ]
            }
            , {
                "title": "常规",
                "icon": "fa fa-address-book",
                "target": "_self",
                "child": [
                    {
                        "title": "模板",
                        "href": "/task/index",
                        "target": "_self",
                    }
                ]
            }
        ]
    },
    )
